import { useState } from "react";
import { FaEye, FaEyeSlash } from "react-icons/fa";
import { LoginApi } from "../../../http/module/LoginRegister/index";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const Navigate = useNavigate();
  const [formData, setFormData] = useState({
    phone: "",
    password: "",
  });

  const [passwordVisible, setPasswordVisible] = useState(false);

  const togglePasswordVisibility = () => setPasswordVisible(!passwordVisible);

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    // Perform login API call
    //设置全局登陆state
    LoginApi(formData).then((response) => {
      if (response.code === 200) {
        window.localStorage.setItem("isLogin", true);
        alert("Login successful!");
        Navigate("/user");
      } else {
        alert("Login failed!");
      }
    });
    alert("Logging in...");
  };

  return (
    <div className="max-w-sm mx-auto mt-12 p-6 bg-white rounded-lg shadow-lg">
      <h2 className="text-2xl font-semibold text-center text-gray-800 mb-6">
        Login
      </h2>
      <form onSubmit={handleSubmit} className="space-y-6">
        <div>
          <label className="block text-sm font-medium text-gray-700">
            Phone
          </label>
          <input
            type="text"
            name="phone"
            value={formData.phone}
            onChange={handleChange}
            required
            className="w-full px-4 py-3 mt-1 border rounded-lg focus:ring focus:ring-blue-200 shadow-sm"
            placeholder="Enter your phone number"
          />
        </div>

        <div className="relative">
          <label className="block text-sm font-medium text-gray-700">
            Password
          </label>
          <input
            type={passwordVisible ? "text" : "password"}
            name="password"
            value={formData.password}
            onChange={handleChange}
            required
            className="w-full px-4 py-3 mt-1 border rounded-lg focus:ring focus:ring-blue-200 shadow-sm"
            placeholder="Enter your password"
          />
          <button
            type="button"
            className="absolute right-3 top-10 text-gray-600"
            onClick={togglePasswordVisibility}
          >
            {passwordVisible ? <FaEyeSlash /> : <FaEye />}
          </button>
        </div>

        <button
          type="submit"
          className="w-full py-3 text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition shadow-md"
        >
          Login
        </button>
      </form>
    </div>
  );
};

export default Login;
